
import sys

from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import Qt, QSettings,QCoreApplication
from PyQt5.QtGui import QColor
from core.menubar import MenuBar
from core.themecolor import ThemeColor
from PyQt5.QtGui import QPainter, QColor, QIcon, QPaintEvent, QMouseEvent

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__(None)
        self.setup_ui()
        self.setWindowFlags(Qt.FramelessWindowHint)

    def setup_ui(self):

        self.setWindowFlags(Qt.FramelessWindowHint)

        settings = QSettings("setting.ini", QSettings.IniFormat)
        color_value = settings.value("bgColor", "0x505050")

        try:
            color = QColor(color_value)
            if color.isValid():
                ThemeColor.setBaseColor(color)
        except:
            ThemeColor.setBaseColor(QColor(0x50, 0x50, 0x50))

        self.m_menubar = MenuBar(self)
        self.setMenuWidget(self.m_menubar)
        self.init_style_sheet()

    def init_style_sheet(self):
        try:
            # 1. 获取QApplication实例
            app = QApplication.instance()
            if app is None:
                raise RuntimeError("无法获取QApplication实例")

            with open("style.qss", "r", encoding='utf-8') as file:
                style_content = file.read()
                app.setStyleSheet(style_content)  # 应用到整个应用程序

        except FileNotFoundError:
            print("错误：未找到style.qss文件")
        except UnicodeDecodeError:
            print("错误：文件编码问题，请使用UTF-8格式")
        except Exception as e:
            print(f"加载样式表失败: {str(e)}")

    def closeEvent(self, event):
        super().closeEvent(event)

    def paintEvent(self, event):
        painter = QPainter(self)
        color = ThemeColor.baseColor()
        color.setAlphaF(0.7)
        painter.fillRect(event.rect(), color)